<?php

namespace app\api\controller;

use app\admin\model\nav\Category;
use think\facade\Cache;
use think\facade\Db;
use Throwable;
use think\Response;
use app\common\library\Upload;
use app\common\controller\Frontend;

class Ajax extends Frontend
{
    protected array $noNeedLogin = ['area', 'buildSuffixSvg', 'navList', 'browse'];

    protected array $noNeedPermission = ['upload'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function upload(): void
    {
        $file   = $this->request->file('file');
        $driver = $this->request->param('driver', 'local');
        $topic  = $this->request->param('topic', 'default');
        try {
            $upload     = new Upload();
            $attachment = $upload
                ->setFile($file)
                ->setDriver($driver)
                ->setTopic($topic)
                ->upload(null, 0, $this->auth->id);
            unset($attachment['create_time'], $attachment['quote']);
        } catch (Throwable $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    /**
     * 省份地区数据
     * @throws Throwable
     */
    public function area(): void
    {
        $this->success('', get_area());
    }

    public function buildSuffixSvg(): Response
    {
        $suffix     = $this->request->param('suffix', 'file');
        $background = $this->request->param('background');
        $content    = build_suffix_svg((string)$suffix, (string)$background);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/svg+xml');
    }

    // 获取分类和相关的导航数据
    public function navList()
    {
        #region网站浏览次数记录=====
        $ip = $this->request->ip();

        $check = Cache::get($ip);
        if ($check === null) {
            // 更新数据库浏览次数
            Db::name('config')->where('name', 'number_of_views')->setInc('value');

            // 记录一次访问
            Cache::set($ip, 1, 3600); // 缓存一小时
        }
        #endregion

        #region导航数据相关=====
        $domain = get_sys_config('domain');
        $data = (new Category())
            ->where('switch', 1)
            ->with([
                'assNav' => function ($query) {
                    $query->where('is_show', 1)->order('sort', 'desc');
                }
            ])
            ->select();
        #endregion

        $this->success(data: [
            'nav_list' => $data,
            'config' => [
                'domain' => $domain
            ]
        ]);
    }
}